<?php

namespace App\Models\Chanjet;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class TplusSaleInvoice extends Model
{
    protected $table = 'tplus_sale_invoice';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];
    public static function getList(Request $request, $memberinfo, $isgetall)
    {
        $cpid = $memberinfo['cpid'] ?? 0;
        $where  [] = ['cpid',$cpid];
        $pid = $request->pid;
        $voucher_code = $request->voucher_code?? '';
        $settle_customer = $request->settle_customer?? '';

        if($pid){
            $where  [] = ['id',$pid];
        }
        if(!empty($voucher_code)){
            $where  [] = ['voucher_code','like','%'.$voucher_code.'%'];
        }

        if(!empty($settle_customer)){
            $where  [] = ['settle_customer','like','%'.$settle_customer.'%'];
        }
        $query = self::with("info")->where($where)->orderBy("voucher_time","desc")->orderBy("voucher_id","desc");

        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }
    /**
     * 获取详情
     */
    public function info()
    {
        return $this->hasMany(TplusSaleInvoiceInfo::class,'main_id','id');
    }
    public static function getSettleCustomerList(Request $request, $memberinfo, $isgetall){
        $cpid = $memberinfo['cpid'] ?? 0;
        $where[] = ['cpid','=',$cpid];
        $where[] = ['settle_customer','<>',''];
        $query = self::where($where);
        $list = $query->select(["settle_customer"])->distinct('settle_customer')->get()->toArray();
        if(!empty($list)){
            foreach ($list as $key=>&$item){
                $item['id'] = $key+1;
            }
        }
        return ['list' => $list];
    }
}
